//
//  SSComposeView.swift
//  weibo
//
//  Created by 邵帅 on 16/6/30.
//  Copyright © 2016年 groupNineObject. All rights reserved.
//

import UIKit
import pop

enum ComposeAnimateType: Int{
    
    case UP = 0
    case DOWN = 1
}

class SSComposeView: UIView {
    
    // 定义数组保存按钮
    private lazy var composeButtons: [UIButton] = [UIButton]()
    var viewControlelr: UIViewController?

    // 第一步 -- 重写构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 第二步 -- 定义一个方法,来实现 视图的添加和布局
    private func setupUI(){
        
        // 改变背景颜色
        backgroundColor = UIColor.yellowColor()
        // 设置一下frmae
        var frame = self.frame
        
        frame.size = UIScreen.mainScreen().bounds.size
        
        self.frame = frame
        
        
        addSubview(bgImageView)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.snp_edges)
            
        }
        
        addButtons()
        
    }
    // 添加按钮的方法
    private func addButtons(){
        
        // 0 .设置一下固定值
        let maxRow = 3
        let childButtonW: CGFloat = 80
        let childButtonH: CGFloat = 110
        let childButtonMargin = ( UIScreen.mainScreen().bounds.size.width - 3 * childButtonW ) / (CGFloat(maxRow) + 1)
        
        
        
        // 1. 读取plist文件
        let composeArray = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!)!
        
        
        // 2. 对数组进行遍历
        for i in 0..<composeArray.count {
            
            
            // 3
            let button = SSComposeButton()
            
            // 4. 拿到数据
            //  as! 只要程序员敢保证前边的数据有值,而且类型也正确就可以 as!
            let imageString = composeArray[i]["icon"] as! String
            let title = composeArray[i]["title"] as! String
            // 设置图片
            button.setImage(UIImage(named: imageString), forState: .Normal)
            // 设置标题
            button.setTitle(title, forState: .Normal)
            
            button.addTarget(self, action: #selector(SSComposeView.btnClick(_:)), forControlEvents: .TouchUpInside)
            
            
            // 5. 设置frame
            
            button.frame.size = CGSizeMake(childButtonW, childButtonH)
            
            // x = margin * (列 + 1) + width * (列)
            // 列
            let col = i % (maxRow)
            // 行
            let row = i / maxRow
            
            button.frame.origin.x = childButtonMargin * CGFloat(col + 1) + childButtonW * CGFloat(col)
            // y = margin * 行 + height * 行
            
            button.frame.origin.y = childButtonMargin * CGFloat(row) + childButtonH * CGFloat(row) + UIScreen.mainScreen().bounds.height
            
            addSubview(button)
            
            // 添加到数组
            composeButtons.append(button)
        }
        
        
    }
    
    // 动画
    private func addButtonAnimation(button: UIButton,time: CFTimeInterval,type: ComposeAnimateType) {
        
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        if type == .UP {
            
            anim.toValue = NSValue(CGPoint: CGPointMake(button.center.x, button.center.y - UIScreen.mainScreen().bounds.height + 300))
        }else if type == .DOWN {
            
            anim.toValue = NSValue(CGPoint: CGPointMake(button.center.x, button.center.y + UIScreen.mainScreen().bounds.height))
        }
        
        // 弹性反弹
        anim.springBounciness = 4
        
        anim.springSpeed = 10
        
        // 动画开始时间
        anim.beginTime = time
        
        // 添加动画
        button.pop_addAnimation(anim, forKey: nil)
    }
    
    // 实现动画
    func show(){
        
        for (index,button) in composeButtons.enumerate() {
            
            addButtonAnimation(button, time: CACurrentMediaTime() + 0.03 * Double(index), type: .UP)
        }
    }
    
    // touch方法
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        for (index,button) in composeButtons.reverse().enumerate() {
            
            addButtonAnimation(button, time: CACurrentMediaTime() + 0.03 * Double(index), type: .DOWN)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
            
            self.removeFromSuperview()
        }
        
    }
    
    // 按钮的点击
    @objc private func btnClick(sender: UIButton){
    
        UIView.animateWithDuration(0.3, animations: {
            
            for btn in self.composeButtons {
                
                btn.alpha = 0
                
                if btn == sender {
                    
                    btn.transform = CGAffineTransformMakeScale(2, 2)
                }else {
                    
                    btn.transform = CGAffineTransformMakeScale(0.3, 0.3)
                }
                
            }

            
            }) { (_) in
                
                let publishViewController = SSPublishViewController()
                
                let nav = UINavigationController(rootViewController: publishViewController)
                
                self.viewControlelr?.presentViewController(nav, animated: true, completion: nil)
                
                self.removeFromSuperview()
        }
    }
    
    
    // MARK:-- 获取当前屏幕的截图
    func getScreenShot() -> UIImage{
        
        
        // 1. 先要获取一下当前的window
        let window = UIApplication.sharedApplication().keyWindow!
        // 2. 开启绘图
        /*
         size: 大小
         opaque:是否透明
         scale: 缩放系数
         */
        UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, 1)
        
        // 3. 把window画在画板上
        window.drawViewHierarchyInRect(UIScreen.mainScreen().bounds, afterScreenUpdates: false)
        
        // 4. 拿到image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        // 5. 关闭画板
        UIGraphicsEndImageContext()
        
        return image
    }
    
    // 第三步: 懒加载控件
    private lazy var bgImageView: UIImageView = {
        
        let img = UIImageView()
        
        img.image = self.getScreenShot()
        
        // iOS 8 之后,系统为我们提供了一个毛玻璃效果
        //
        let effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        
        // 创建一个毛玻璃视图
        let effectView = UIVisualEffectView(effect: effect)
        
        // 把这个毛玻璃添加到 img
        img.addSubview(effectView)
        
        // 设置毛玻璃视图的约束
        effectView.snp_makeConstraints(closure: { (make) -> Void in
            make.edges.equalTo(img.snp_edges)
        })
        
        return img
    }()


}
